/*
 *  libKara - Library for basic instant messaging functions
 *  Copyright (C) 2007 Markus Karnik
 *
 *  This program is free software; you can redistribute it and/or modify it 
 *  under the terms of the GNU General Public License as published by the
 *  Free Software Foundation; either version 3 of the License, 
 *  or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 *  or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 *  for more details.
 *
 *  You should have received a copy of the GNU General Public License along 
 *  with this program; if not, see <http://www.gnu.org/licenses/>.
 *  
 */

package de.karnik.libkara.proto.xmpp;

import java.util.Vector;

import de.karnik.libkara.pluginspecs.BaseProtocol;
import de.karnik.libkara.proto.xmpp.packages.XmlPackage;
import de.karnik.libkara.proto.xmpp.packages.XmlPackageStorage;
import de.karnik.libkara.proto.xmpp.packages.XmppIQChildBind;
import de.karnik.libkara.proto.xmpp.packages.XmppIQChildRoster;
import de.karnik.libkara.proto.xmpp.packages.XmppIQChildSession;
import de.karnik.libkara.proto.xmpp.packages.XmppIQStanza;
import de.karnik.libkara.proto.xmpp.packages.XmppMessageStanza;
import de.karnik.libkara.proto.xmpp.packages.XmppPresenceStanza;
import de.karnik.libkara.proto.xmpp.packages.XmppStanzaReaderListener;
import de.karnik.libkara.roster.ImMessage;

/**
 * Reads and processes the incoming packages.
 * 
 * @author Markus Karnik - markus.karnik@my-design.org
 * @version 1.0
 * @since 1.0
 */
public class XmppStanzaReaderThread extends Thread {

	/**
	 * Indicates if current thread is running.
	 */
	private boolean running = false;
	/**
	 * The package storage to read from.
	 */
	private XmlPackageStorage packageStorage = null;
	/**
	 * The thread listener for callbacks.
	 */
	private XmppThreadListener threadListener = null; 
	/**
	 * The unique thread id.
	 */
	private String threadID = "standard";
	/**
	 * The current XMPP client settings.
	 */
	private XmppSettings xmppSettings = null;
	
	/**
	 * The stanza listener storage.
	 */
	private Vector<XmppStanzaReaderListener> stanzaListeners = new Vector<XmppStanzaReaderListener>( 1, 1 );
	
	/**
	 * Constructs a stanza reader thread with the given initial values.
	 * 
	 * @param threadID The thread id.
	 * @param packageStorage The package storage to read from.
	 * @param xmppSettings The XMPP settings to use.
	 */
	public XmppStanzaReaderThread(  String threadID, XmlPackageStorage packageStorage, XmppSettings xmppSettings ) {
		this.packageStorage = packageStorage;
		this.threadID = threadID;
		this.xmppSettings = xmppSettings;
	}
	
	/**
	 * Removes the given stanza listener.
	 * 
	 * @param stanzaListener The stanza listener to remove.
	 */
	public void removeXmppStanzaListern( XmppStanzaReaderListener stanzaListener ){
		this.stanzaListeners.remove( stanzaListener );
	}
	
	/**
	 * Adds the given stanza listener.
	 * 
	 * @param stanzaListener The stanza listener to add.
	 */
	public void addXmppStanzaListener( XmppStanzaReaderListener stanzaListener ) {
		this.stanzaListeners.add( stanzaListener );
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Thread#run()
	 */
	public void run() {
		this.startReading();
	}
	
	/**
	 *  Start reading the stanzas.
	 */
	private void startReading() {

		// create temp vars
		XmlPackage xmlPackage = null;
		this.running = true;
		
		// send started to the listener
		if( this.threadListener != null )
			this.threadListener.threadStarted( this.threadID );
		
		// while the thread is running an a package storage is available 
		while( this.running && ( this.packageStorage != null ) ) {
		
			try {
				// read next output package
				xmlPackage = this.packageStorage.getNextInputPackage();
			} catch ( InterruptedException e ) {
				// send interrupted to the listener
				if( this.threadListener != null )
					this.threadListener.threadInterrupted( this.threadID );				
			}
			
			// process message stanzas
			if( xmlPackage instanceof XmppMessageStanza ) {
				this.analyseMessageStanza( ( XmppMessageStanza )xmlPackage );
				
			// process iq stanzas				
			} else if( xmlPackage instanceof XmppIQStanza ) {
				this.analyseIQStanza( ( XmppIQStanza )xmlPackage );
				
			// process presence stanzas
			} else if( xmlPackage instanceof XmppPresenceStanza ) {	
				this.analysePresenceStanza( ( XmppPresenceStanza )xmlPackage );
				
			}
		}
		
		// send stop signal to the listener
		if( this.threadListener != null )
			this.threadListener.threadStopped( this.threadID );
	}
	
	/**
	 * Analyses the given message stanza.
	 * 
	 * @param message The message stanza to analyze.
	 */
	public void analyseMessageStanza( XmppMessageStanza message ) {
		ImMessage newMessage = null;
		
		// chat message
		if( message.getType() != null && message.getType().equals( XmppMessageStanza.TYPE_CHAT )
				&& message.getFrom() != null && message.isBodyAvailable() )  {
			
			
			newMessage = new ImMessage( message.getDefaultChildSubject(), message.getDefaultChildBody() );
			
			for( int i = 0; i < this.stanzaListeners.size(); i++ )
				this.stanzaListeners.get( i ).messageArrived( 
						XmppProtocol.stripResourceFromUserId( message.getFrom() ), newMessage );
		}
	}
	
	/**
	 * Analyses the given presence stanza.
	 * 
	 * @param presence The presence stanza to analyze.
	 */
	public void analysePresenceStanza( XmppPresenceStanza presence ) {
		int status;

		// just status stuff
		if( presence.getType() == null && presence.getFrom() != null )  {
			
			// parse status
			if( presence.getChildShow() != null )
				status = XmppProtocol.getKaraStatus( presence.getChildShow() );
			else
				status =  BaseProtocol.STATUS_AVAILABLE;	
			
			for( int i = 0; i < this.stanzaListeners.size(); i++ )
				this.stanzaListeners.get( i ).contactStatusChanged( 
						XmppProtocol.stripResourceFromUserId( presence.getFrom() ), status, null );

		}
		
	}
	
	/**
	 * Analyses the given iq stanza.
	 * 
	 * @param iq The iq stanza to analyze.
	 */
	public void analyseIQStanza( XmppIQStanza iq ) {
		if( iq.getType() != null && iq.getId()!= null ) {
			// analyse bind package
			if( iq.getChild() instanceof XmppIQChildBind ) {
				// if type is a result and the id equals client resouce id the client is bound to the resource
				if( iq.getType().equals( XmppIQStanza.TYPE_RESULT ) 
						&& iq.getId().equals( this.xmppSettings.getStringData( XmppSettings.STRING_VALUE_RESOURCEID ) ) ) { 
					this.xmppSettings.putBooleanData( XmppSettings.BOOLEAN_VALUE_BOUND, true );
					
					// inform all listener
					for( int i = 0; i < this.stanzaListeners.size(); i++ ) {
						this.stanzaListeners.get( i ).connectionBound();
					}
				}
				
			} else if( iq.getChild() instanceof XmppIQChildSession ) {
				
				// if type is a result and the id equals current session id the session is established
				if( iq.getType().equals( XmppIQStanza.TYPE_RESULT ) 
						&& iq.getId().equals( this.xmppSettings.getStringData( XmppSettings.STRING_VALUE_SESSIONID ) ) ) { 
					this.xmppSettings.putBooleanData( XmppSettings.BOOLEAN_VALUE_SESSION_ESTABLISHED, true );
					
					// inform all listener
					for( int i = 0; i < this.stanzaListeners.size(); i++ ) {
						this.stanzaListeners.get( i ).sessionEstablished();
					}
				}
			
			} else if( iq.getChild() instanceof XmppIQChildRoster ) {
							
				// analyse result types
				if( iq.getType().equals( XmppIQStanza.TYPE_RESULT ) ) {
					if( iq.getId() != null ) {
						// result is the roster
						if( iq.getId().equals( XmppIQStanza.ID_GET_ROSTER ) && ( iq.getChild() instanceof XmppIQChildRoster ) ) {
								
							XmppIQChildRoster rosterChild = ( XmppIQChildRoster )iq.getChild();
							
							for( int i = 0; i < rosterChild.getXmppRosterItems().size(); i++ ) {

								for( int j = 0; j < this.stanzaListeners.size(); j++ ) {
									this.stanzaListeners.get( j ).contactReceived( 
											rosterChild.getXmppRosterItems().get( i ).getJid(), 
											rosterChild.getXmppRosterItems().get( i ).getName(), 
											rosterChild.getXmppRosterItems().get( i ).getSubscription(), 
											rosterChild.getXmppRosterItems().get( i ).getGroups() );
								}

							}
							// inform all listener
							for( int i = 0; i < this.stanzaListeners.size(); i++ ) 
								this.stanzaListeners.get( i ).rosterCompleted();
						}
					}
					
				} else if( iq.getType().equals( XmppIQStanza.TYPE_GET ) ) {
				} else if( iq.getType().equals( XmppIQStanza.TYPE_SET ) ) {
				} else if( iq.getType().equals( XmppIQStanza.TYPE_ERROR ) ) {
				}
				
				
				
			}
		} else {
			// TODO no id and no type
		}
		
	}
	
	/**
	 * Removes the current XmppThreadListener.
	 */
	public void removeThreadListener() {
		this.threadListener = null;
	}

	/**
	 * Sets the current XmppThreadListener.
	 * 
	 * @param threadListener The XmppThreadListener for thread callbacks.
	 */
	public void setThreadListener( XmppThreadListener threadListener ) {
		this.threadListener = threadListener;
	}
		
	/**
	 * Shuts down the current thread.
	 */
	public void shutdown() {
		this.running = false;
		this.packageStorage.interruptInput();
	}
	
}
